# -*- coding: utf-8 -*-
# @Time : 2024/8/12 17:06
# @Author : Junior
import random
import subprocess
import time

import uiautomation as auto


class AutoSearch(object):

    def __init__(self, app_path):
        self.app_path = app_path
        self.window = self.open_app()
        self.keywords = []

    def open_app(self):
        try:
            # 打開應用
            subprocess.Popen(self.app_path)
            time.sleep(5)
            # 窗口捕获
            window = auto.WindowControl(ClassName="Chrome_WidgetWin_1")
            # 設置窗口最大化
            window.Maximize()
            # 窗口置顶
            # window.SetTopmost()
            time.sleep(2)
            print("打開 edge 完成, 并执行搜索...")

            return window

        except Exception as e:
            print(f"打开 edge 出現錯誤：{e}")

    def search(self, search_item_id):
        search_keywords = self.get_random_keywords()
        for keyword in search_keywords:
            search_input = auto.EditControl(AutomationId=search_item_id)
            search_input.SendKeys(keyword)
            auto.SendKeys('{Enter}')
            time.sleep(5)
            while True:
                time.sleep(1)
                title = auto.PaneControl(ClassName="BrowserRootView").Name
                if keyword in title:
                    search_input.SendKeys("{Ctrl}{A}")
                    break

    def get_random_keywords(self):
        self.read_keywords()
        return random.sample(self.keywords, 35)

    def read_keywords(self):
        with open('keywords.txt', 'r', encoding='utf-8') as file:
            # 读取所有行到列表中
            self.keywords = [line.strip() for line in file]


if __name__ == "__main__":
    print("开始执行账号: 1353815638@qq.com 搜索任务......")
    first_one = AutoSearch(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe")
    # first_one.search("view_1022")
    # 关闭浏览器
    auto.ButtonControl(AutomationId="view_7").Click()
    time.sleep(1)
    print("账号: 1353815638@qq.com 搜索任务完成")

    print("开始执行账号: 1620249184@qq.com 搜索任务......")
    second_one = AutoSearch(r"D:\edge\Edge_118.0.5993.69_64bit_Portable\Edge\msedge.exe")
    second_one.search("view_1020")
    # 关闭浏览器
    auto.ButtonControl(AutomationId="view_7").Click()
    time.sleep(1)
    print("账号: 1620249184@qq.com 搜索任务完成")
